package org.itboys.mobile.service.mongo.weixin;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.question.SundayAnswerDto;
import org.itboys.mobile.dto.question.SundayQuestionDetailDto;
import org.itboys.mobile.dto.question.SundayQuestionDto;
import org.itboys.mobile.entity.mongo.SundayExpert;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.SundayQuestion;
import org.itboys.mobile.service.mongo.web.SundayExpertService;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author：贾琦磊
 * @Date：2018/7/19
 * @Description：微信端问答
 */
@Service
public class SundayWeiXinQuestionService extends BaseMongoService<SundayQuestion> {
    @Resource(name = "mobileDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }
    @Override
    protected Class<SundayQuestion> getEntityClass() {
        return SundayQuestion.class;
    }

    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayExpertService expertService;

    /**
     * 用户提出问题
     * @param memberId
     * @param content
     * 所有问答没有修改功能，只能删除
     */
    public void save(Long memberId,String content){
        /**
         * 用户提出问题父id为0，且初始状态待审核状态，用户端不进行展示
         */
        SundayQuestion question=new SundayQuestion(memberId,0L,content, SundayCommonConstants.comment_type_unchecked);
        super.save(question);
    }

    /**
     * 分页查询所有问答，查询已审核通过的问答
     * @param request
     * @return
     */
    public List<SundayQuestionDto> getAllQuestions(HttpServletRequest request,Long memberId){
        //先定义返回结果集
        List<SundayQuestionDto> result=new ArrayList<>();
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request);
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("parentId",0L);
        param.put("sort","ct");
        param.put("order","desc");
        if(LongUtil.isNotZreo(memberId)){
            param.put("memberId",memberId);
        }else {
            param.put("status",SundayCommonConstants.comment_type_pass);
        }
        /**
         * 获取所有问题，定义问题回答父id集合，匹配每条问题最近一次回答
         * 定义所有用户id集合，查询相关用户信息
         */
        List<Long> answerPIds=new ArrayList<>();
        List<Long> memberIds=new ArrayList<>();
        List<SundayQuestion> questions = super.containpageQuery(request, null, param).getData();
        for (SundayQuestion question:questions) {
            answerPIds.add(question.getId());
            memberIds.add(question.getMemberId());
        }
        //根据降序排列所有回答，取最近发布的一条数据封装dto
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("parentId in",answerPIds);
        param.put("sort","ct");
        param.put("order","desc");
        List<SundayQuestion> answers = super.list(param);
        List<Long> expertIds=new ArrayList<>();
        for (SundayQuestion question:answers) {
            expertIds.add(question.getMemberId());
        }
        //获取所有相关专家
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("id in" ,expertIds);
        List<SundayExpert> experts = expertService.list(param);
        param.put("id in",memberIds);
        List<SundayMember> members = memberService.list(param);
        //开始封装dto
        for (SundayQuestion question:questions) {
            int num=0;
            SundayQuestionDto dto=new SundayQuestionDto();
            //封装问题部分信息
            dto.setId(question.getId());
            dto.setQuestionContent(question.getContent());
            dto.setQuestionDate(question.getCreateDate());
            for (SundayMember member:members) {
                if(question.getMemberId().longValue()==member.getId()){
                    dto.setMemberName(member.getNickName());
                    dto.setMemberImage(member.getImage());
                }
            }
            //封装回答部分信息
            for (SundayQuestion answer:answers){
                if(question.getId()==answer.getParentId().longValue()){
                    //组装回答人信息
                    for (SundayExpert expert:experts) {
                        if(answer.getMemberId().longValue()==expert.getId()){
                            if(dto.getAnswerType()==null){dto.setAnswerType(SundayCommonConstants.user_type_expert);}
                            if(StringUtils.isEmpty(dto.getAnswerName())){dto.setAnswerName(expert.getName());}
                            if(StringUtils.isEmpty(dto.getAnswerImage())){dto.setAnswerImage(expert.getImage());}
                        }
                    }
                    //防止重复set回答时间和内容
                    if(StringUtils.isEmpty(dto.getAnswerDate())){ dto.setAnswerDate(answer.getCreateDate());}
                    if(StringUtils.isEmpty(dto.getAnswerContent())){ dto.setAnswerContent(answer.getContent());}
                    num++;
                }
            }
            dto.setNum(num);
            result.add(dto);
        }
        return result;
    }

    /**
     *
     * @param id
     * @return
     */
    public SundayQuestionDetailDto getDetail(Long id){
        SundayQuestionDetailDto result=new SundayQuestionDetailDto();
        SundayQuestion question = super.getById(id);
        result.setQuestionContent(question.getContent());
        result.setQuestionDate(question.getCreateDate());
        SundayMember member=memberService.getById(question.getMemberId());
        if(member!=null){
            result.setMemberImage(member.getImage());
            result.setMemberName(member.getNickName());
        }
        //获取所有答案
        Map<String,Object> param=new HashedMap();
        param.put("parentId",id);
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("sort","ct");
        param.put("order","desc");
        //获取所有的相关用户
        List<Long > memberIds=new ArrayList<>();
        List<Long> expertIds=new ArrayList<>();
        List<SundayQuestion> answers = super.list(param);
        for (SundayQuestion answer:answers) {
            expertIds.add(answer.getMemberId());
        }
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("id in",expertIds);
        List<SundayExpert> experts = expertService.list(param);
        List<SundayAnswerDto> answerDtos=new ArrayList<>();
        for (SundayQuestion answer:answers) {
            SundayAnswerDto answerDto=new SundayAnswerDto();
            for (SundayExpert expert:experts) {
                if(expert.getId()==answer.getMemberId().longValue()){
                    answerDto.setName(expert.getName());
                    answerDto.setImage(expert.getImage());
                    answerDto.setUserType(SundayCommonConstants.user_type_expert);
                }
            }
            answerDto.setContent(answer.getContent());
            answerDto.setDate(answer.getCreateDate());
            answerDtos.add(answerDto);
        }
        result.setAnswers(answerDtos);
        result.setNum(answerDtos.size());
        return result;
    }

}
